import { useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import Creator from "../store/actions";
// 引入api
import TypesApi from "../api/types";

export const useTypes = () => {
    // 获取全部父类型数据
    const types = useSelector(state => {
        return state.getAll
    })
    const dispatch = useDispatch();
    const { curPage, eachPage } = types;
    // 操作状态的行为
    // 添加父类型
    const addTypes = useCallback(async ({ title }) => {
        const newType = await TypesApi.add({ title });
        return newType;
        // dispatch(Creator.addTypes({newType}));
    }, [])
    
    // 修改当前页
    const setCurPage=useCallback(curPage=>{
        dispatch(Creator.setCurPage({curPage}));
    },[dispatch])

    // 修改每页显示条数
    const setEachPage=useCallback(eachPage=>{
        dispatch(Creator.setEachPage({eachPage}));
    },[dispatch])

    // 获取所有父类型
    const getTypes = useCallback(async () => {
        const data = await TypesApi.getAll({ curPage, eachPage })
        console.log(data);
        dispatch(Creator.getAll(data));
    }, [curPage, eachPage, dispatch]);

    // 获取所有父类型
    const getAllTypes = useCallback(async () => {
        const data = await TypesApi.getTypes()
        dispatch(Creator.getAllTypes({data}));
    }, [dispatch]);

    return [types, { addTypes, getTypes,setCurPage,setEachPage,getAllTypes}]

}